<?php
/**
 * 字典库
 * User: lxl
 * Date: 2020/07/22
 */

namespace App\Service\Core\Sys\Dict;

use App\Component\ListService\ListAbstract;
use App\Model\Core\Sys\SysDictModel;
use App\Service\ParamsService;
use Illuminate\Database\Query\Builder;

/**
 * @method  $this setDictSubVal($val)
 * @method  $this setDictItem($val)
 */
class SysDictListService extends ListAbstract
{

    //允许获取的字段
    protected array $allow_fields = ['*'];

    //扩展字段
    protected array $allow_ext_fields = ['dict_item_name'];

    //默认排序
    protected array $default_sort_by = [
        'sys_dict.sort_order' => 'desc',
        'sys_dict.id' => 'desc',
    ];

    /**
     * 字典列表
     * @return Builder
     */
    protected function getQueryObj(): Builder
    {
        $query_obj = SysDictModel::getInstance()->getConnectionTable();

        //字典项搜索
        $dict_item = $this->getParam('dict_item');
        if (!empty($dict_item)) {
            $query_obj->where('sys_dict.dict_item', $dict_item);
        }

        //字典子值搜索
        $dict_sub_val = $this->getParam('dict_sub_val');
        if (!empty($dict_sub_val)) {
            $query_obj->where('sys_dict.dict_sub_val', 'like', '%' . $dict_sub_val . '%');
        }

        return $query_obj;
    }

    /**
     * 扩展字段
     * @param array $row
     * @return array
     */
    protected function getExtField(array $row): array
    {
        //字典项
        if (easy_in_array('dict_item_name', $this->ext_fields)) {
            $row['dict_item_name'] = ParamsService::$dict_item_list[$row['dict_item']];
        }
        return $row;
    }
}
